import { fileURLToPath, URL } from "node:url"
import { defineConfig, loadEnv } from "vite"
import AutoImport from "unplugin-auto-import/vite"
import Components from "unplugin-vue-components/vite"
import { ElementPlusResolver } from "unplugin-vue-components/resolvers"
import vue from "@vitejs/plugin-vue"
import { createHtmlPlugin } from "vite-plugin-html"
//这个配置 为了在html中使用 环境变量
const getViteEnv = (mode: any, target: any) => {
  return loadEnv(mode, process.cwd())[target]
}
// https://vitejs.dev/config/
export default defineConfig({
  // base: "./",
  server: {
    host: "0.0.0.0", // 启动后浏览器窗口输入地址就可以进行访问
    port: 4444, // 端口号
    open: true, //是否自动打开浏览器
    cors: true, //为开发服务器配置 CORS , 默认启用并允许任何源
    // https: false, //是否支持http2 如果配置成true 会打开https://localhost:3001/xxx;
    strictPort: true, //是否是严格的端口号，如果true，端口号被占用的情况下，vite会退出
    hmr: true,
    proxy: {
      "^/api": {
        target: loadEnv("", process.cwd()).VITE_APP_BASE_URL, //跨域地址
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
  plugins: [
    vue(),
    createHtmlPlugin({
      inject: {
        data: {
          //将环境变量 VITE_APP_TITLE 赋值给 title 方便 html页面使用 title 获取系统标题
          title: getViteEnv("dev", "VITE_APP_NAME"),
        },
      },
    }),
    AutoImport({
      imports: ["vue", "vue-router"],
      resolvers: [ElementPlusResolver()],
      eslintrc: { enabled: true },
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
  //打包前先清空原有打包文件
  build: {
    emptyOutDir: true,
  },

  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
})
